package com.csthink.web.infrastructure.mq.consumer;

import com.csthink.mq.payload.RocketMessage2;
import com.csthink.mq.rocketmq.enhance.EnhanceMessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import static com.csthink.web.infrastructure.constant.AsyncMQConstants.ROCKETMQ_TAG_DELETE;

/**
 * 演示如何使用 EnhanceMessageHandler {@link EnhanceMessageHandler}
 * @author <a href="mailto:security.2009@live.cn">Mars</a>
 * @since 2023-09-07
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "group_rocketmq3",
        topic = "${async.mq.rocket.subscriber.topic.practice-practice2}",
        selectorExpression = ROCKETMQ_TAG_DELETE)
public class EnhanceRocketMQMessageListener extends EnhanceMessageHandler<RocketMessage2>
        implements RocketMQListener<RocketMessage2> {
    @Override
    protected void handleMessage(RocketMessage2 message) throws Exception {
        // 此时这里才是最终的业务处理，代码只需要处理资源类关闭异常，其他的可以交给父类重试
        log.info("业务消息处理: {}", message);
        log.info("业务消息处理: {}", message.getUsername());
    }

    @Override
    protected void handleMaxRetriesExceeded(RocketMessage2 message) {
        // 当超过指定重试次数消息时此处方法会被调用
        // 生产中可以进行回退或其他业务操作
        log.error("消息消费失败，请执行后续处理");
    }

    @Override
    protected boolean isRetry() {
        return true;
    }

    @Override
    protected boolean throwException() {
        // 是否抛出异常，false搭配retry自行处理异常
        return false;
    }

//    @Override
//    protected boolean filter(RocketMessage2 message) {
        // 消息过滤
//        return true;
//    }

    /**
     * 监听消费消息，不需要执行业务处理，委派给父类做基础操作，父类做完基础操作后会调用子类的实际处理类型
     *
     * @param rocketMessage2
     */
    @Override
    public void onMessage(RocketMessage2 rocketMessage2) {
        super.dispatchMessage(rocketMessage2);
    }
}
